//
//  SearchViewController.m
//  ZPIOSEducation
//
//  Created by 董伟1 on 17/1/10.
//  Copyright © 2017年 mini1. All rights reserved.
//

#import "SearchViewController.h"
#import "SearchCell.h"
#import "ZPCourseViewController.h"

#define DeleteAlertTag  1000

@interface SearchViewController () <UITextFieldDelegate,UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
{
    UIView  *headerView;
    NSMutableArray  *dataArray;
}

@property (weak, nonatomic) IBOutlet UITextField *searchField;
@property (weak, nonatomic) IBOutlet UITableView *mainTableView;

@end

@implementation SearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.searchField.delegate = self;
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;
    
    NSArray  *tempArray = [[NSUserDefaults  standardUserDefaults] objectForKey:@"SearchHistory"];
    if (tempArray) {
        dataArray = [[NSMutableArray  alloc] initWithArray:tempArray];
    }else {
        dataArray = [[NSMutableArray  alloc] init];
    }
    
    if (dataArray.count > 0) {
        self.mainTableView.tableHeaderView = [self  createTableHeaderView];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (UIView  *)createTableHeaderView
{
    if (!headerView) {
        headerView = [[UIView  alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 40)];
        headerView.backgroundColor = [UIColor  whiteColor];
        
        UILabel  *titleLab = [[UILabel  alloc] initWithFrame:CGRectMake(20, 24, 100, 14)];
        titleLab.text = @"最近搜索";
        titleLab.textColor = RGBACOLOR(153, 153, 153, 1.);
        titleLab.font = [UIFont  systemFontOfSize:12.];
        titleLab.backgroundColor = [UIColor  clearColor];
        [headerView  addSubview:titleLab];
        
        UIButton  *deleteBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        deleteBtn.frame = CGRectMake(SCREENWIDTH - 50, 8, 44, 30);
        [deleteBtn  setImage:[UIImage  imageNamed:@"Search_Delete"] forState:UIControlStateNormal];
        [deleteBtn  setBackgroundColor:[UIColor  clearColor]];
        [deleteBtn  addTarget:self action:@selector(deleteButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [headerView  addSubview:deleteBtn];
    }
    
    return headerView;
    
    
}

- (void)managerHistoryWithStr:(NSString  *)string
{
    if (string.length == 0) {
        return;
    }
    NSInteger  count = [dataArray  count];
    for (int i = 0; i < count; i ++) {
        NSString  *tempStr = [dataArray  objectAtIndex:i];
        if ([tempStr  isEqualToString:string]) {
            [dataArray  removeObject:tempStr];
            break;
        }
    }
    
    if (dataArray.count == 0) {
        [dataArray  addObject:string];
    }else {
        [dataArray  insertObject:string atIndex:0];
    }
    
    if (dataArray.count > 15) {
        NSRange range = NSMakeRange(15, dataArray.count - 15);
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [dataArray removeObjectsAtIndexes:indexSet];
    }
    
    NSUserDefaults  *userDefault = [NSUserDefaults  standardUserDefaults];
    [userDefault setObject:dataArray forKey:@"SearchHistory"];
    [userDefault  synchronize];
    
    if (dataArray.count > 0) {
        self.mainTableView.tableHeaderView = [self  createTableHeaderView];
    }else {
        self.mainTableView.tableHeaderView = nil;
    }
    [self.mainTableView  reloadData];
    
    ZPCourseViewController  *viewController = [[ZPCourseViewController  alloc] initWithNibName:@"ZPCourseViewController" bundle:nil];
    viewController.searchText = string;
    viewController.fromSearch = YES;
    [self.navigationController  pushViewController:viewController animated:YES];
}

#pragma mark - Button Actions
#pragma mark 取消按钮
- (IBAction)cancelButtonClick:(id)sender
{
    [self  dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 删除按钮
- (void)deleteButtonClick
{
    UIAlertView  *alert = [[UIAlertView  alloc] initWithTitle:@"" message:@"确认清空搜索历史吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"清空", nil];
    alert.tag = DeleteAlertTag;
    [alert  show];
}

#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.;
}

- (UITableViewCell  *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"SearchCell";
    SearchCell  *cell = (SearchCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SearchCell" owner:self options:nil] lastObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    NSInteger  row = [indexPath  row];
    cell.titleLab.text = [dataArray  objectAtIndex:row];
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString  *searchStr = [dataArray  objectAtIndex:indexPath.row];
    [self  managerHistoryWithStr:searchStr];
}

#pragma mark - UIScrollView Delegate
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.searchField  resignFirstResponder];
}

#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == DeleteAlertTag && buttonIndex == 1) {
        [dataArray  removeAllObjects];
        
        NSUserDefaults  *userDefault = [NSUserDefaults  standardUserDefaults];
        [userDefault setObject:dataArray forKey:@"SearchHistory"];
        [userDefault  synchronize];
        
        if (dataArray.count > 0) {
            self.mainTableView.tableHeaderView = [self  createTableHeaderView];
        }else {
            self.mainTableView.tableHeaderView = nil;
        }
        [self.mainTableView  reloadData];
    }
}

#pragma mark - UITextField Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    //去掉首尾空格
    NSString  *searchStr = [textField.text  stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (searchStr.length == 0) {
        UIAlertView  *alert = [[UIAlertView  alloc] initWithTitle:@"提示" message:@"输入不正确,请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert  show];
    }else {
        [self  managerHistoryWithStr:searchStr];
    }
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
